package com.apr.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义Filter
 * @author zlj
 */
public class MyFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("{}", "MyFilter 初始化了---");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.info("{}", "MyFilter 执行了---");
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String origin = request.getHeader("Origin");
        if(!StringUtils.isEmpty(origin)) {
            //设置允许访问的域，带* 不能满足带cookie的跨域请求
            response.addHeader("Access-Control-Allow-Origin", origin);
        }

        //设置允许访问的方法
        response.addHeader("Access-Control-Allow-Methods", "*");

        String header = request.getHeader("Access-Control-Request-Headers");
        if(!StringUtils.isEmpty(header)) {
            //设置相应头
            response.addHeader("Access-Control-Allow-Headers", "Content-Type,x-header1,x-header2");
        }

        //缓冲预检命令
        response.addHeader("Access-Control-Max-Age", "3600");

        //带Cookie的跨域需要这个字段的值为true
        response.addHeader("Access-Control-Allow-Credentials", "true");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.info("{}", "MyFilter 销毁了---");
    }
}
